package com.meiyuetao.myt.partner.web.action;

import java.util.List;
import java.util.Map;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.security.AclService;
import lab.s2jh.core.security.AuthContextHolder;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.web.annotation.SecurityControlIgnore;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.md.entity.Brand;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.partner.entity.Partner;
import com.meiyuetao.myt.partner.entity.PartnerR2Brand;
import com.meiyuetao.myt.partner.entity.PartnerR2Commodity;
import com.meiyuetao.myt.partner.service.PartnerService;
import com.meiyuetao.myt.sale.entity.BoxOrder.OrderFromEnum;

@MetaData("合作伙伴")
public class PartnerController extends MytBaseController<Partner, Long> {

    @Autowired
    private PartnerService partnerService;
    @Autowired
    private AclService aclService;

    @Override
    protected BaseService<Partner, Long> getEntityService() {
        return partnerService;
    }

    @Override
    protected void setupDetachedBindingEntity(Long id) {
        bindingEntity = getEntityService().findDetachedOne(id, "partnerR2Brands", "partnerR2Commodities");
    }

    @Override
    protected void checkEntityAclPermission(Partner entity) {

    }

    @Override
    @MetaData("删除")
    public HttpHeaders doDelete() {
        return super.doDelete();
    }

    @Override
    protected void appendFilterProperty(GroupPropertyFilter groupPropertyFilter) {
        if (groupPropertyFilter.isEmpty()) {
            groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.NU, "parent", true));
        }
        super.appendFilterProperty(groupPropertyFilter);

    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    @Override
    public HttpHeaders doSave() {

        if (bindingEntity.isNew()) {
            bindingEntity.addExtraAttribute("signinid", getRequiredParameter("signinid"));
            bindingEntity.addExtraAttribute("newpassword", getRequiredParameter("newpassword"));
        }

        return super.doSave();
    }

    public Map<String, String> getOrderFroms() {
        Map<String, String> dataMap = Maps.newHashMap();
        OrderFromEnum[] orderFromEnums = OrderFromEnum.values();
        for (OrderFromEnum e : orderFromEnums) {
            MetaData metaData = FieldUtils.getDeclaredField(OrderFromEnum.class, e.name()).getAnnotation(MetaData.class);
            dataMap.put(e.name(), metaData.value());
        }
        return dataMap;
    }

    @MetaData(value = "列表")
    @SecurityControlIgnore
    public HttpHeaders treeDatas() {
        List<Partner> items = Lists.newArrayList();
        List<Map<String, Object>> treeDatas = Lists.newArrayList();
        String aclCodePrefix = AuthContextHolder.getAclCodePrefix();
        if (StringUtils.isBlank(aclCodePrefix)) {
            List<Partner> roots = partnerService.findRoots();
            String partnerType = getParameter("partnerType");
            if (StringUtils.isNotBlank(partnerType)) {
                for (Partner root : roots) {
                    if (root.getPartnerType() != null && partnerType.equals(root.getPartnerType().name())) {
                        items.add(root);
                    }
                }
            } else {
                items.addAll(roots);
            }
        } else {
            items.add(partnerService.findByCode(AuthContextHolder.getAclCode()));
        }
        for (Partner item : items) {
            loopTreeData(treeDatas, item);
        }
        setModel(treeDatas);
        return buildDefaultHttpHeaders();
    }

    private void loopTreeData(List<Map<String, Object>> treeDatas, Partner item) {
        Map<String, Object> row = Maps.newHashMap();
        treeDatas.add(row);
        row.put("id", item.getId());
        row.put("name", item.getDisplay());
        row.put("contactPhone", item.getContactPhone());
        row.put("contactPerson", item.getContactPerson());
        row.put("address", item.getAddress());
        row.put("postCode", item.getPostCode());
        row.put("level", item.getLevel());
        row.put("open", false);
        List<Partner> children = partnerService.findChildren(item);
        if (!CollectionUtils.isEmpty(children)) {
            List<Map<String, Object>> childrenList = Lists.newArrayList();
            row.put("children", childrenList);
            for (Partner child : children) {
                loopTreeData(childrenList, child);
            }
        }
    }

    @MetaData("代理品牌列表")
    public HttpHeaders partnerR2Brands() {
        List<PartnerR2Brand> r2s = bindingEntity.getPartnerR2Brands();
        if (BooleanUtils.toBoolean(getParameter("clone"))) {
            for (PartnerR2Brand r2 : r2s) {
                r2.resetCommonProperties();
            }
        }
        setModel(buildPageResultFromList(r2s));
        return buildDefaultHttpHeaders();
    }

    @MetaData("代理商品列表")
    public HttpHeaders partnerR2Commodities() {
        List<PartnerR2Commodity> r2s = bindingEntity.getPartnerR2Commodities();
        if (BooleanUtils.toBoolean(getParameter("clone"))) {
            for (PartnerR2Commodity r2 : r2s) {
                r2.resetCommonProperties();
            }
        }
        setModel(buildPageResultFromList(r2s));
        return buildDefaultHttpHeaders();
    }

    @MetaData("代理商关联的商品列表")
    public HttpHeaders relationedCommodities() {
        List<Commodity> commodities = partnerService.getRelationedCommodities(bindingEntity);
        setModel(buildPageResultFromList(commodities));
        return buildDefaultHttpHeaders();
    }

    @MetaData("代理商关联的品牌列表")
    public HttpHeaders relationedBrands() {
        List<Brand> brands = partnerService.getRelationedBrands(bindingEntity);
        setModel(buildPageResultFromList(brands));
        return buildDefaultHttpHeaders();
    }
}